<template>
  <div class="content-card">
    <div class="page-header">
      <h2>支付对账</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleReconciliation">执行对账</el-button>
        <el-button @click="handleExport">导出对账数据</el-button>
      </div>
    </div>
    
    <!-- 对账搜索筛选 -->
    <el-form :model="searchForm" class="search-form">
      <el-form-item label="对账日期" prop="date">
        <el-date-picker
          v-model="searchForm.date"
          type="date"
          placeholder="请选择对账日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-select v-model="searchForm.paymentMethod" placeholder="请选择支付方式">
          <el-option label="全部" value="" />
          <el-option label="支付宝" value="1" />
          <el-option label="微信支付" value="2" />
          <el-option label="银行卡" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="对账状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择对账状态">
          <el-option label="全部" value="" />
          <el-option label="待对账" value="0" />
          <el-option label="对账成功" value="1" />
          <el-option label="存在差异" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 对账概览 -->
    <div class="reconciliation-overview">
      <div class="overview-card">
        <div class="overview-title">待对账</div>
        <div class="overview-value pending-count">{{ pendingCount }}</div>
      </div>
      <div class="overview-card">
        <div class="overview-title">对账成功</div>
        <div class="overview-value success-count">{{ successCount }}</div>
      </div>
      <div class="overview-card">
        <div class="overview-title">存在差异</div>
        <div class="overview-value diff-count">{{ diffCount }}</div>
      </div>
    </div>
    
    <!-- 对账记录表格 -->
    <el-table 
      v-loading="loading" 
      :data="reconciliationList" 
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="reconciliationDate" label="对账日期" width="150" />
      <el-table-column prop="paymentMethod" label="支付方式" width="120">
        <template #default="scope">
          {{ getPaymentMethodText(scope.row.paymentMethod) }}
        </template>
      </el-table-column>
      <el-table-column prop="localTotalAmount" label="系统总金额" width="120" formatter="formatPrice" />
      <el-table-column prop="channelTotalAmount" label="渠道总金额" width="120" formatter="formatPrice" />
      <el-table-column prop="localCount" label="系统订单数" width="120" />
      <el-table-column prop="channelCount" label="渠道订单数" width="120" />
      <el-table-column prop="differenceAmount" label="金额差异" width="120" formatter="formatPrice" />
      <el-table-column prop="differenceCount" label="订单数差异" width="120" />
      <el-table-column prop="status" label="对账状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" width="180" />
      <el-table-column prop="handledBy" label="处理人" width="100" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleViewDetail(scope.row)">查看详情</el-button>
          <el-button v-if="scope.row.status === 2" type="warning" size="small" @click="handleProcessDiff(scope.row)">处理差异</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination">
      <div class="pagination-info">
        共 {{ total }} 条记录，每页显示 {{ pageSize }} 条
      </div>
      <el-pagination 
        v-model:current-page="currentPage" 
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 批量操作 -->
    <div class="batch-actions" v-if="selectedReconciliations.length > 0">
      <el-button type="primary" @click="handleBatchReconciliation">批量对账</el-button>
      <el-button type="warning" @click="handleBatchProcessDiff">批量处理差异</el-button>
      <el-button @click="handleBatchExport">批量导出</el-button>
    </div>
  </div>
</template>

<script>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { paymentApi } from '../../api/payment.js'

export default {
  name: 'PaymentReconciliation',
  setup() {
    const loading = ref(false)
    const reconciliationList = ref([])
    const selectedReconciliations = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // 对账统计数据
    const pendingCount = ref(5)
    const successCount = ref(23)
    const diffCount = ref(2)
    
    // 搜索表单
    const searchForm = reactive({
      date: '',
      paymentMethod: '',
      status: ''
    })
    
    // 格式化价格
    const formatPrice = (row, column, cellValue) => {
      return `¥${cellValue.toFixed(2)}`
    }
    
    // 获取支付方式文本
    const getPaymentMethodText = (method) => {
      const methodMap = {
        1: '支付宝',
        2: '微信支付',
        3: '银行卡'
      }
      return methodMap[method] || '未知'
    }
    
    // 获取状态标签类型
    const getStatusTagType = (status) => {
      switch (status) {
        case 0: return 'info'
        case 1: return 'success'
        case 2: return 'warning'
        default: return 'default'
      }
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 0: return '待对账'
        case 1: return '对账成功'
        case 2: return '存在差异'
        default: return '未知状态'
      }
    }
    
    // 获取对账记录列表
    const getReconciliationList = async () => {
      loading.value = true
      try {
        const params = {
          ...searchForm,
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }
        
        // 模拟API请求，使用mock数据
        setTimeout(() => {
          reconciliationList.value = generateMockData()
          total.value = 30
          loading.value = false
        }, 500)
        
        // 实际API调用代码（目前注释掉）
        // const response = await paymentApi.getReconciliationList(params)
        // reconciliationList.value = response.data.list
        // total.value = response.data.total
        // loading.value = false
      } catch (error) {
        console.error('获取对账记录列表失败:', error)
        ElMessage.error('获取对账记录列表失败')
        loading.value = false
      }
    }
    
    // 生成模拟数据
    const generateMockData = () => {
      const reconciliations = []
      
      for (let i = 0; i < pageSize.value; i++) {
        const index = (currentPage.value - 1) * pageSize.value + i + 1
        const paymentMethod = Math.floor(Math.random() * 3) + 1
        
        // 随机状态，但确保有不同状态的数据
        let status = Math.floor(Math.random() * 3)
        // 如果是特定索引，强制设置特定状态以确保多样性
        if (index % 5 === 0) status = 0
        if (index % 7 === 0) status = 2
        
        // 基础金额和数量
        const baseAmount = Math.floor(Math.random() * 100000) + 10000
        const baseCount = Math.floor(Math.random() * 200) + 50
        
        let localTotalAmount, channelTotalAmount, localCount, channelCount, differenceAmount, differenceCount
        
        if (status === 1) {
          // 对账成功，金额和数量一致
          localTotalAmount = baseAmount
          channelTotalAmount = baseAmount
          localCount = baseCount
          channelCount = baseCount
          differenceAmount = 0
          differenceCount = 0
        } else {
          // 待对账或有差异
          if (status === 0) {
            // 待对账，数据为空
            localTotalAmount = 0
            channelTotalAmount = 0
            localCount = 0
            channelCount = 0
            differenceAmount = 0
            differenceCount = 0
          } else {
            // 有差异
            localTotalAmount = baseAmount
            channelTotalAmount = baseAmount + Math.floor(Math.random() * 1000) - 500
            localCount = baseCount
            channelCount = baseCount + Math.floor(Math.random() * 20) - 10
            differenceAmount = localTotalAmount - channelTotalAmount
            differenceCount = localCount - channelCount
          }
        }
        
        // 生成日期（最近30天内）
        const date = new Date()
        date.setDate(date.getDate() - (index % 30))
        const dateStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
        
        reconciliations.push({
          id: index,
          reconciliationDate: dateStr,
          paymentMethod: paymentMethod,
          localTotalAmount: localTotalAmount,
          channelTotalAmount: channelTotalAmount,
          localCount: localCount,
          channelCount: channelCount,
          differenceAmount: differenceAmount,
          differenceCount: differenceCount,
          status: status,
          createdTime: new Date(date.getTime() + 1000 * 60 * 60 * 8).toLocaleString(), // 模拟创建时间
          handledBy: status === 1 ? `admin${Math.floor(Math.random() * 10)}` : ''
        })
      }
      
      return reconciliations
    }
    
    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1
      getReconciliationList()
    }
    
    // 处理重置
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      currentPage.value = 1
      getReconciliationList()
    }
    
    // 处理分页大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size
      currentPage.value = 1
      getReconciliationList()
    }
    
    // 处理当前页码变化
    const handleCurrentChange = (current) => {
      currentPage.value = current
      getReconciliationList()
    }
    
    // 处理选择变化
    const handleSelectionChange = (selection) => {
      selectedReconciliations.value = selection
    }
    
    // 执行对账
    const handleReconciliation = async () => {
      if (!searchForm.date) {
        ElMessage.warning('请选择对账日期')
        return
      }
      
      try {
        // 显示确认对话框
        await ElMessageBox.confirm(
          `确定要对 ${searchForm.date} 的数据执行对账吗？`,
          '确认对账',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 模拟对账请求
        loading.value = true
        setTimeout(() => {
          ElMessage.success('对账执行成功')
          getReconciliationList()
          // 更新统计数据
          pendingCount.value -= 1
          successCount.value += 1
        }, 1500)
        
        // 实际API调用代码（目前注释掉）
        // await paymentApi.doReconciliation(searchForm)
        // ElMessage.success('对账执行成功')
        // getReconciliationList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('执行对账失败:', error)
          ElMessage.error('执行对账失败')
        }
        loading.value = false
      }
    }
    
    // 处理查看详情
    const handleViewDetail = (reconciliation) => {
      // 这里可以打开详情弹窗或者跳转到详情页面
      ElMessage.info(`查看对账详情：${reconciliation.reconciliationDate} - ${getPaymentMethodText(reconciliation.paymentMethod)}`)
    }
    
    // 处理差异
    const handleProcessDiff = async (reconciliation) => {
      try {
        // 显示确认对话框
        await ElMessageBox.confirm(
          `确定要处理 ${reconciliation.reconciliationDate} - ${getPaymentMethodText(reconciliation.paymentMethod)} 的对账差异吗？`,
          '确认处理差异',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 模拟处理差异请求
        loading.value = true
        setTimeout(() => {
          ElMessage.success('差异处理成功')
          getReconciliationList()
          // 更新统计数据
          diffCount.value -= 1
          successCount.value += 1
        }, 1500)
        
        // 实际API调用代码（目前注释掉）
        // await paymentApi.processReconciliationDiff(reconciliation.id)
        // ElMessage.success('差异处理成功')
        // getReconciliationList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('处理差异失败:', error)
          ElMessage.error('处理差异失败')
        }
        loading.value = false
      }
    }
    
    // 批量对账
    const handleBatchReconciliation = async () => {
      try {
        // 显示确认对话框
        await ElMessageBox.confirm(
          `确定要对选中的 ${selectedReconciliations.value.length} 条记录执行批量对账吗？`,
          '确认批量对账',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 模拟批量对账请求
        loading.value = true
        setTimeout(() => {
          ElMessage.success(`批量对账成功，共处理 ${selectedReconciliations.value.length} 条记录`)
          getReconciliationList()
          selectedReconciliations.value = []
          // 更新统计数据
          pendingCount.value -= selectedReconciliations.value.filter(item => item.status === 0).length
          successCount.value += selectedReconciliations.value.length
        }, 1500)
        
        // 实际API调用代码（目前注释掉）
        // const ids = selectedReconciliations.value.map(item => item.id)
        // await paymentApi.batchReconciliation(ids)
        // ElMessage.success(`批量对账成功，共处理 ${selectedReconciliations.value.length} 条记录`)
        // getReconciliationList()
        // selectedReconciliations.value = []
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量对账失败:', error)
          ElMessage.error('批量对账失败')
        }
        loading.value = false
      }
    }
    
    // 批量处理差异
    const handleBatchProcessDiff = async () => {
      try {
        // 过滤出有差异的记录
        const diffRecords = selectedReconciliations.value.filter(item => item.status === 2)
        if (diffRecords.length === 0) {
          ElMessage.warning('请选择有差异的记录')
          return
        }
        
        // 显示确认对话框
        await ElMessageBox.confirm(
          `确定要对选中的 ${diffRecords.length} 条差异记录执行批量处理吗？`,
          '确认批量处理差异',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 模拟批量处理差异请求
        loading.value = true
        setTimeout(() => {
          ElMessage.success(`批量处理差异成功，共处理 ${diffRecords.length} 条记录`)
          getReconciliationList()
          selectedReconciliations.value = []
          // 更新统计数据
          diffCount.value -= diffRecords.length
          successCount.value += diffRecords.length
        }, 1500)
        
        // 实际API调用代码（目前注释掉）
        // const ids = diffRecords.map(item => item.id)
        // await paymentApi.batchProcessReconciliationDiff(ids)
        // ElMessage.success(`批量处理差异成功，共处理 ${diffRecords.length} 条记录`)
        // getReconciliationList()
        // selectedReconciliations.value = []
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量处理差异失败:', error)
          ElMessage.error('批量处理差异失败')
        }
        loading.value = false
      }
    }
    
    // 导出对账数据
    const handleExport = async () => {
      try {
        // 模拟导出请求
        loading.value = true
        setTimeout(() => {
          ElMessage.success('对账数据导出成功')
          loading.value = false
        }, 1500)
        
        // 实际API调用代码（目前注释掉）
        // await paymentApi.exportReconciliationData(searchForm)
        // ElMessage.success('对账数据导出成功')
      } catch (error) {
        console.error('导出对账数据失败:', error)
        ElMessage.error('导出对账数据失败')
        loading.value = false
      }
    }
    
    // 批量导出
    const handleBatchExport = async () => {
      try {
        const ids = selectedReconciliations.value.map(item => item.id)
        // 模拟批量导出请求
        loading.value = true
        setTimeout(() => {
          ElMessage.success('批量导出成功')
          loading.value = false
        }, 1500)
        
        // 实际API调用代码（目前注释掉）
        // await paymentApi.batchExportReconciliation(ids)
        // ElMessage.success('批量导出成功')
      } catch (error) {
        console.error('批量导出失败:', error)
        ElMessage.error('批量导出失败')
        loading.value = false
      }
    }
    
    // 初始化数据
    onMounted(() => {
      getReconciliationList()
    })
    
    return {
      loading,
      reconciliationList,
      selectedReconciliations,
      total,
      currentPage,
      pageSize,
      searchForm,
      pendingCount,
      successCount,
      diffCount,
      formatPrice,
      getPaymentMethodText,
      getStatusTagType,
      getStatusText,
      handleSearch,
      handleReset,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      handleReconciliation,
      handleViewDetail,
      handleProcessDiff,
      handleBatchReconciliation,
      handleBatchProcessDiff,
      handleExport,
      handleBatchExport
    }
  }
}
</script>

<style scoped lang="scss">
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .header-actions {
    .el-button {
      margin-left: 10px;
    }
  }
}

.search-form {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  
  .el-form-item {
    margin-right: 20px;
    margin-bottom: 15px;
  }
}

.reconciliation-overview {
  display: flex;
  margin-bottom: 20px;
  
  .overview-card {
    flex: 1;
    text-align: center;
    padding: 20px;
    background-color: #f9f9f9;
    border-radius: 4px;
    margin-right: 20px;
    
    &:last-child {
      margin-right: 0;
    }
    
    .overview-title {
      color: var(--text-secondary);
      font-size: 14px;
      margin-bottom: 10px;
    }
    
    .overview-value {
      font-size: 24px;
      font-weight: bold;
      
      &.pending-count {
        color: #409eff;
      }
      
      &.success-count {
        color: #67c23a;
      }
      
      &.diff-count {
        color: #e6a23c;
      }
    }
  }
}

.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  
  .pagination-info {
    color: var(--text-secondary);
    font-size: 14px;
  }
}

.batch-actions {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
  
  .el-button {
    margin-right: 10px;
  }
}
</style>